package com.cnswhy.cloud.server.merchant.controller.spell;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.base.request.PageParams;
import com.cnswhy.cloud.common.core.entity.CurrentUser;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.core.utils.DateUtils;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.PayType;
import com.cnswhy.cloud.server.common.entity.enumeration.TransType;
import com.cnswhy.cloud.server.common.entity.enumeration.WalletType;
import com.cnswhy.cloud.server.common.entity.mq.OrderQueryMQ;
import com.cnswhy.cloud.server.common.entity.mq.SpellDayendCancelMsg;
import com.cnswhy.cloud.server.common.entity.mq.SpellMsg;
import com.cnswhy.cloud.server.core.appservice.AppSpellOrderService;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dao.SpellOrderMapper;
import com.cnswhy.cloud.server.core.dto.*;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.oem.OemService;
import com.cnswhy.cloud.server.core.service.SpellInfoService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-16
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/spellOrder")
@Api(value = "SpellOrder", tags = "")
//@PreAuth(replace = "spellOrder:")
public class SpellOrderController extends SuperController<SpellOrderService, Long, SpellOrder, SpellOrderPageDTO, SpellOrderSaveDTO, SpellOrderUpdateDTO> {
    @Autowired
    MessageService messageService;
    @Autowired
    SpellOrderMapper spellOrderMapper;
    @PostMapping("/spell")
    public R<Boolean> queryCan(Long id){
        SpellOrder spellOrder = baseService.getById(id);
        SpellMsg spellMsg = SpellMsg.builder().id(spellOrder.getId()).build();
        spellMsg.setTraceId(MDCUtil.getTraceId());
        messageService.sendQueueByObject(AmqpExchange.SPELL_MESSAGE,spellMsg);
        return success();
    }
    @Autowired
    AppSpellOrderService appSpellOrderService;
    @PostMapping("/notifySpellOrder")
    public R<Boolean> notifySpellOrder(String tradeNo,String outTradeNo, PayType payType){
        appSpellOrderService.notifySpellOrder(tradeNo, outTradeNo, payType);

        return success();
    }
    @Autowired
    CustomerService customerService;
    @Autowired
    WalletService walletService;

    @Autowired
    RedisService redisService;
    @Autowired
    IdGeneratorService idGeneratorService;

    @ApiOperation(value = "订单查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNum", value = "订单号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "payType", value = "交易类型(ALIPAY or WXPAY)", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/sendQueryOrder", method = {RequestMethod.GET})
    @ResponseBody
    public RespVo sendQueryOrder(String orderNum, PayType payType) {
        log.info("接到订单查询请求:{},{}", orderNum, payType);
        RespVo vo = new RespVo();
        try {
            OrderQueryMQ orderQueryMQ = OrderQueryMQ.builder().orderId(orderNum).queryTimes(0L).build();
            orderQueryMQ.setPayType(payType);
            orderQueryMQ.setBody("SPELL-SHOPPING");
            orderQueryMQ.setTraceId(MDCUtil.getTraceId());
            messageService.sendAndQueryTimes(AmqpExchange.ORDER_QUERY_MESSAGE, orderQueryMQ, orderQueryMQ.getQueryTimes());
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("请求成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("请求失败");
            log.error("请求失败", e);
        }
        return vo;
    }
    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    /*@ApiOperation(value = "分页列表查询商品明细")
    @PostMapping(value = "/shopProductDetailPage")
    //@SysLog(value = "'分页列表查询:第' + #params?.current + '页, 显示' + #params?.size + '行'", response = false)
    //@PreAuth("hasPermit('{}view')")
    public R<IPage<ShopProductDetail>> shopProductDetailPage(@RequestBody @Validated PageParams<ShopProductDetailPageDTO> params) {
        // 处理参数
        IPage<ShopProductDetail> page = params.buildPage();
        //query1(params, page, null);
        CurrentUser currentUser = CnswhyUtil.getCurrentUser();
        log.info(JSON.toJSONString(currentUser));
        if(currentUser.getMerchantId() != null){
            params.getModel().setMerchantId(currentUser.getMerchantId());
        }
        page = shopProductMapper.getShopProductDetails(page,params.getModel());
        for(ShopProductDetail shopProductDetail : page.getRecords()){
            shopProductDetail.setShopProductGalleryList(shopProductGalleryService.list(Wraps.<ShopProductGallery>lbQ().eq(ShopProductGallery::getProductId,shopProductDetail.getId())));
            shopProductDetail.setShopProductSpecList(shopProductSpecService.list(Wraps.<ShopProductSpec>lbQ().eq(ShopProductSpec::getProductId,shopProductDetail.getId())));
            shopProductDetail.setShopProductStockList(shopProductStockService.list(Wraps.<ShopProductStock>lbQ().eq(ShopProductStock::getProductId,shopProductDetail.getId())));
        }
        return success(page);
    }*/
    @ApiOperation(value = "分页查询发货拼团订单")
    @PostMapping(value = "/getSendListPage")
    //@SysLog(value = "'分页列表查询:第' + #params?.current + '页, 显示' + #params?.size + '行'", response = false)
    //@PreAuth("hasPermit('{}view')")
    public R<IPage<SpellOrderDetail>> getSendList(@RequestBody @Validated PageParams<SpellOrderDetailPageDTO> params) {
        // 处理参数

        Map<String, String> map = params.getMap();
        if(StringUtils.isNotBlank(map.get("createTime_st"))){
            params.getModel().setCreateDateSt(DateUtils.getStartTime(map.get("createTime_st")));
        }
        if(StringUtils.isNotBlank(map.get("createTime_ed"))){
            params.getModel().setCreateDateEnd(DateUtils.getStartTime(map.get("createTime_ed")));
        }
        params.getModel().setStatus(3);
        params.getModel().setGoodsType(2);
        IPage<SpellOrderDetail> page = params.buildPage();
        //query1(params, page, null);
        page = spellOrderMapper.getSendList(page,params.getModel());
        return success(page);
    }
    @ApiOperation(value = "分页查询发货拼团订单")
    @PostMapping(value = "/getSpellPage")
    //@SysLog(value = "'分页列表查询:第' + #params?.current + '页, 显示' + #params?.size + '行'", response = false)
    //@PreAuth("hasPermit('{}view')")
    public R<IPage<SpellOrderDetail>> getSpellPage(@RequestBody @Validated PageParams<SpellOrderDetailPageDTO> params) {
        // 处理参数
        //params.getModel().setStatus(3);
        //params.getModel().setGoodsType(2);
        if(StringUtils.isNotBlank(params.getModel().getPromoterMobile())){
            Customer customer = customerService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName,params.getModel().getPromoterMobile()));
            if(customer != null){
                params.getModel().setPromoterList(customer.getPromoterList());
            }
        }
        IPage<SpellOrderDetail> page = params.buildPage();
        Map<String, String> map = params.getMap();
        if(StringUtils.isNotBlank(map.get("createTime_st"))){
            params.getModel().setCreateDateSt(DateUtils.getStartTime(map.get("createTime_st")));
        }
        if(StringUtils.isNotBlank(map.get("createTime_ed"))){
            params.getModel().setCreateDateEnd(DateUtils.getStartTime(map.get("createTime_ed")));
        }
        //query1(params, page, null);
        page = spellOrderMapper.getSpellList(page,params.getModel());
        return success(page);
    }
    @ApiOperation(value = "导出Excel")
    //@RequestMapping(value = "/export1", method = RequestMethod.POST, produces = "application/octet-stream")
    @RequestMapping(value = "/export1", method = RequestMethod.POST)
    //@SysLog("'导出Excel:'.concat(#params.map[" + NormalExcelConstants.FILE_NAME + "]?:'')")
    //@PreAuth("hasPermit('{}export')")
    public R<Boolean> exportExcel1(@RequestBody @Validated PageParams<SpellOrderDetailPageDTO> params, HttpServletRequest request, HttpServletResponse response) {
        /*params.setSize(65535L);*/
        if(StringUtils.isNotBlank(params.getModel().getPromoterMobile())){
            Customer customer = customerService.getOne(Wraps.<Customer>lbQ().eq(Customer::getLoginName,params.getModel().getPromoterMobile()));
            if(customer != null){
                params.getModel().setPromoterList(customer.getPromoterList());
            }
        }
        Map<String, String> ma1p = params.getMap();
        if(StringUtils.isNotBlank(ma1p.get("createTime_st"))){
            params.getModel().setCreateDateSt(DateUtils.getStartTime(ma1p.get("createTime_st")));
        }
        if(StringUtils.isNotBlank(ma1p.get("createTime_ed"))){
            params.getModel().setCreateDateEnd(DateUtils.getStartTime(ma1p.get("createTime_ed")));
        }
        SpellOrderDetailPageDTO spellOrderDetailPageDTO = params.getModel();
        if(StringUtils.isBlank(spellOrderDetailPageDTO.getSettDate())){
            return R.fail("请选择日期");
        }
        ExportParams exportParams = getExportParams1(params);

        Map<String, Object> map = new HashMap<>(5);
        List<SpellOrderDetail> spellOrders = spellOrderMapper.exportSpellList(params.getModel());

        map.put(NormalExcelConstants.DATA_LIST, spellOrders);
        map.put(NormalExcelConstants.CLASS, SpellOrderDetail.class);
        map.put(NormalExcelConstants.PARAMS, exportParams);
        String fileName = params.getMap().getOrDefault(NormalExcelConstants.FILE_NAME, "临时文件");
        map.put(NormalExcelConstants.FILE_NAME, fileName);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
        return R.success();
    }
    /**
     * 构建导出参数
     *
     * @param params 分页参数
     * @return
     */
    public ExportParams getExportParams1(PageParams<SpellOrderDetailPageDTO> params) {
        log.info(JSON.toJSONString(params));

        String title = params.getMap().get("title");
        String type = params.getMap().getOrDefault("type", ExcelType.XSSF.name());
        String sheetName = params.getMap().getOrDefault("sheetName", "SheetName");

        ExcelType excelType = ExcelType.XSSF.name().equals(type) ? ExcelType.XSSF : ExcelType.HSSF;
        return new ExportParams(title, sheetName, excelType);
    }
    /**/
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<SpellOrder> spellOrderList = list.stream().map((map) -> {
            SpellOrder spellOrder = SpellOrder.builder().build();
            return spellOrder;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(spellOrderList));
    }

    @Autowired
    OemService oemService;
    @Autowired
    SpellInfoService spellInfoService;
    @Autowired
    SpellOrderService spellOrderService;
}
